from flask import Flask, g, render_template, send_from_directory, request, jsonify, url_for, redirect,  session
from flask_session import Session
import os

app = Flask(__name__, template_folder='templates/', static_folder='templates/',static_url_path='')
app.config['SESSION_TYPE'] = 'filesystem'
app.config['SECRET_KEY'] = os.urandom(24)
Session(app)

import pymysql
import time
import json

# 打开数据库连接
db = pymysql.connect(host='localhost',
                     user='root',
                     password='123456',
                     database='fire_test')
# 使用cursor()方法获取操作游标
cursor = db.cursor()

@app.route('/', methods=['GET'])
def index():
    return render_template("login.html")

@app.route('/login', methods=['GET', 'POST'])
def login():
    print("This is login pages!")
    if request.method == 'POST':
        username = request.form.get('username')
        print(username)
        password = request.form.get('password')
        print(password)
        if username == 'admin' and password == '123456':
            session["username"] = username
            return redirect(url_for('questionList'))
        return render_template("login.html")
    return render_template("login.html")

@app.route('/questionList', methods=['GET'])
def questionList():
    username = session["username"]  # 传递全局变量
    return render_template("questionList.html")

@app.route('/adminAction', methods=['GET'])
def adminAction():
    username = session["username"]  # 传递全局变量
    return render_template("adminAction.html")

@app.route('/adddata', methods=['POST'])
def adddata():

    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())
    print(now)
    print(request.data)
    a = request.data
    b = json.loads(a)
    fire = b['fire']
    C_Gas = b['C_Gas']
    # SQL 插入语句
    sql = """INSERT INTO fire(fire,
             C_GAS, TIME)
             VALUES ('{}', '{}', '{}')""".format(fire,C_Gas,now)
    print(sql)
    try:
        # 执行sql语句
        cursor.execute(sql)
        # 提交到数据库执行
        db.commit()
        return "success"
    except:
        # 如果发生错误则回滚
        db.rollback()
        return "failed"

@app.route('/getdata', methods=['GET'])
def getdata():
    # SQL 查询语句
    sql = "SELECT * FROM fire order by Time desc "
    try:
        # 执行SQL语句
        cursor.execute(sql)
        # 获取所有记录列表
        results = cursor.fetchall()
        jsondata = {"data":results[:5],"status":1}
        print(jsondata)
        return jsondata
    except:
        print("Error: unable to fetch data")
        return "failed"


if __name__ == '__main__':
    app.run(host="0.0.0.0",port=5000)
